package com.can.config;

import com.can.pojo.User;
import com.can.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的 Realm  ,继承AuthorizingRealm即可
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权 doGetAuthorizationInfo");
        //给用户授予权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录得这个对象
        Subject subjcet = SecurityUtils.getSubject();
        //拿到User对象
        User currentUser = (User) subjcet.getPrincipal(); //从认证方法中 return SimpleAuthenticationInfo(第一个参数) 拿到得当前用户对象

        //设置当前用户的权限
        if(currentUser.getPerms()!=null) { //currentUser.getPerms()为null会报错
            info.addStringPermission(currentUser.getPerms());
        }

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证 doGetAuthenticationInfo");
        //用户名，密码 数据库中取

        UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken;
        //连接数据库  执行
        User user = userService.queryUserByName(userToken.getUsername());  //idea:Ctrl+Alt+B查看实现类方法

        if(user==null){ //没有这个用户
            return null;//返回null 就会抛出异常 UnknownAccountException 用户名不存在
        }

        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

        //可以加密：MD5 e10adc3949ba59abbe56e057f20f883e   MD5盐值加密  e10adc3949ba59abbe56e057f20f883eusername
        //密码认证，shiro做~,加密了
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
